package com.example.mvvmdemo.ui.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.example.mvvmdemo.R;
import com.example.mvvmdemo.databinding.ItemUserBinding;
import com.example.mvvmdemo.model.User;
import java.util.ArrayList;
import java.util.List;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
    
    private List<User> userList = new ArrayList<>();
    private OnUserClickListener onUserClickListener;
    
    public interface OnUserClickListener {
        void onUserClick(User user);
    }
    
    public void setOnUserClickListener(OnUserClickListener listener) {
        this.onUserClickListener = listener;
    }
    
    public void setUserList(List<User> userList) {
        this.userList = userList;
        notifyDataSetChanged();
    }
    
    @NonNull
    @Override
    public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemUserBinding binding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.getContext()),
                R.layout.item_user,
                parent,
                false
        );
        return new UserViewHolder(binding);
    }
    
    @Override
    public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
        User user = userList.get(position);
        holder.bind(user);
    }
    
    @Override
    public int getItemCount() {
        return userList.size();
    }
    
    class UserViewHolder extends RecyclerView.ViewHolder {
        private ItemUserBinding binding;
        
        UserViewHolder(ItemUserBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
        
        void bind(User user) {
            binding.setUser(user);
            binding.executePendingBindings();
            
            binding.getRoot().setOnClickListener(v -> {
                if (onUserClickListener != null) {
                    onUserClickListener.onUserClick(user);
                }
            });
        }
    }
}